package javalight.network.ro.jsonImpl;

import javalight.network.ro.DataObject;

import org.json.JSONException;
import org.json.JSONObject;

public class DataObjectImpl implements DataObject{

	JSONObject object;
	
	public DataObjectImpl()
	{
		object = new JSONObject();
	}
	public DataObjectImpl(String source)
	{
		try {
			object = new JSONObject(source);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}
	
	public DataObjectImpl(JSONObject object)
	{
		this.object = object;
	}
	
	public JSONObject getSource()
	{
		return object;
	}
	
	@Override
	public Object get(String fieldName) {
		try {
			return object.get(fieldName);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void set(String fieldName, Object value) {
		try {
			if(value instanceof DataObjectImpl)
				object.put(fieldName, ((DataObjectImpl)value).getSource());
			else
				object.put(fieldName, value);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public String toString() {
		return object.toString();
	}

	@Override
	public void fromString(String desc) {
		try {
			object = new JSONObject(desc);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}

}
